<template>
  <el-select
    v-model="currentValue"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    :multiple="multiple"
    :size="size"
    :loading="loading"
    @change="handleChange"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
      :disabled="item.disabled"
    >
      <span>{{ item.label }}</span>
    </el-option>
  </el-select>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { getDictData } from '@/utils/dict'

const emit = defineEmits(['update:modelValue', 'change'])

const props = defineProps({
  // 字典类型
  dictType: {
    type: String,
    required: true
  },
  // 绑定值
  modelValue: {
    type: [String, Number, Array],
    default: ''
  },
  // 占位文本
  placeholder: {
    type: String,
    default: '请选择'
  },
  // 是否可以清空选项
  clearable: {
    type: Boolean,
    default: true
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 是否多选
  multiple: {
    type: Boolean,
    default: false
  },
  // 组件尺寸
  size: {
    type: String,
    default: 'default'
  }
})

// 当前值
const currentValue = ref(props.modelValue)

// 选项数据
const options = ref([])

// 加载状态
const loading = ref(false)

// 监听值变化
watch(
  () => props.modelValue,
  (val) => {
    currentValue.value = val
  }
)

// 值变化事件
const handleChange = (val) => {
  emit('update:modelValue', val)
  emit('change', val)
}

// 加载字典数据
const loadDictData = async () => {
  loading.value = true
  try {
    const dictData = await getDictData(props.dictType)
    // 过滤出正常状态的字典项
    options.value = dictData
      .filter(item => item.status === 1)
      .map(item => ({
        label: item.label,
        value: item.value,
        disabled: false
      }))
  } catch (error) {
    console.error('获取字典数据失败', error)
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载字典数据
onMounted(() => {
  loadDictData()
})

// 监听字典类型变化
watch(
  () => props.dictType,
  () => {
    loadDictData()
  }
)
</script> 